<?php

/**
 * Created by PhpStorm.
 * User: shwy
 * Date: 2017/6/2
 * Time: 16:58
 * 供应商管理
 */
class supplier extends MY_Controller
{

    public function __construct()
    {

        parent::__construct();
        $this->load->model('supplier_model');
        $this->load->model('user_model');

        $this->load->library('Qiniu');

    }

    //供应商管理
    public function index()
    {
        $page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $start_position = ''; //初始数据
        $page = ($this->input->get('page')); //获取页码数量
        if (!$page) {
            $num = 1;
            $start_position = ($num - 1) * $page_num;
        } else {
            $start_position = ($page - 1) * $page_num;
        }

        $data = $this->supplier_model->page('supplier', 0, $page_num, $start_position); //limit查询的数据

        if ($data[0]) {
            $viewData = [
                'list' => $data[0],  //这里得到从数据库中的当页数据
                'totalNum' => $data['total_num'], //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        } else {
            $viewData = [
                'list' => '',  //这里得到从数据库中的当页数据
                'totalNum' => $data['total_num'], //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        }


        $this->load->view('admin/supplier/list', $viewData);
    }

    //新增功能
    public function add()
    {
//        print_r($_POST);
//        die();


        // 上传文件，这里的pic是视图中file控件的name属性

        if ($_FILES['generateSeal']['error'] == 0) {
            $mime4 = substr($_FILES['generateSeal']['name'], strrpos($_FILES['generateSeal']['name'], '.')); //取得上传图片的后缀名

            $generateSealName = 'supplier/generateSeal/' . date('YmdHis') . rand(1000, 2000) . $mime4;
            $this->qiniu->upload($_FILES['generateSeal']['tmp_name'], $generateSealName);

            $generateSeal = $this->config->item('qiniu')['url'] . $generateSealName;

        } else {
            $generateSeal = '';
        }


        $data = [
            'code' => $this->input->post('code'),
            'name' => trim($this->input->post('name')),
            'linkman' => trim($this->input->post('linkMan')),
            'phone' => trim($this->input->post('phone')),
            'type' => $_POST['type'], //供应商类型
            'province' => $_POST['province'], //省
            'city' => $_POST['city'], //市
            'district' => $_POST['district'], //区
            'address' => $_POST['province'] . $_POST['city'] . $_POST['district'] . $_POST['address'], //地址
            'createTime' => strtotime(date('Y-m-d')),
            'size' => $this->input->post('size'),
            'nature' => trim($this->input->post('nature')),
            'isProducers' => trim($this->input->post('isProducers')),
            'vender' => trim($this->input->post('vender')),
            'mail' => trim($this->input->post('mail')),
            'note' => trim($this->input->post('note')),
            'bank' => trim($this->input->post('bank')),
            'bankAccount' => trim($this->input->post('bankAccount')),
            'supplierUser' => trim($this->input->post('supplierUser')),
            'supplierPass' => trim($this->input->post('supplierPass')),
            'generateSeal' => $generateSeal,  //公司印章
            'registerNo' => $_POST['registerNo'] //统一社会信用代码
        ];

//        if(!$data['generateSeal']){
//            unset($data['generateSeal']);
//        }


        $resultData = $this->supplier_model->addId($data);


        if ($resultData) {
            //是否会有添加失败的情况?
            $user = [
//            'supplierUser' => $_POST['supplierUser'],
//            'supplierPass' => $_POST['supplierPass'],

                'username' => trim($this->input->post('supplierUser')),
                'nickname' => trim($this->input->post('name')),
                'password' => trim($this->input->post('supplierPass')),
                'role_id' => '供应商',
//                'sex' => $this->input->post('sex'),
                'phone' => $this->input->post('phone'),
//                'section' => $this->input->post('section'), //部门
//                'residence' => $this->input->post('residence'),
//                'card' => $this->input->post('card'),
//                'loginTime' => time(),
                'createTime' => time(),
                'supplierId' => $resultData //新增的供应商id
            ];
            $this->user_model->add($user);


            //添加成功之后请求通联用户注册接口

            $regData = __reg();

            $formatting = json_decode($regData, true);

            $suppData = [
                'partnerUserId' => $formatting['userId']
            ];
            $suppWhere = [
                'id' => $resultData
            ];

            $this->supplier_model->edit($suppData, $suppWhere);


            redirect('/admin/supplier/index?page=1');
        }


    }

    //新增页面
    public function addView()
    {

        $this->load->view('/admin/supplier/add');
    }

    //编辑功能
    public function edit()
    {
        //用户id
//        print_r($_POST);
//        die();

        $where = [
            'id' => $this->input->post('id')
        ];

        if ($_FILES['generateSeal']['error'] == 0) {
            $mime4 = substr($_FILES['generateSeal']['name'], strrpos($_FILES['generateSeal']['name'], '.')); //取得上传图片的后缀名

            $generateSealName = 'supplier/generateSeal/' . date('YmdHis') . rand(1000, 2000) . $mime4;
            $this->qiniu->upload($_FILES['generateSeal']['tmp_name'], $generateSealName);

            $generateSeal = $this->config->item('qiniu')['url'] . $generateSealName;

        } else {
            $generateSeal = '';
        }


        $data = [
            'createTime' => strtotime($this->input->post('createTime')),
            'size' => $this->input->post('size'),
            'nature' => trim($this->input->post('nature')),
            'isProducers' => trim($this->input->post('isProducers')),
            'vender' => trim($this->input->post('vender')),
            'mail' => $this->input->post('mail'),
            'note' => trim($this->input->post('note')),
            'bank' => trim($this->input->post('bank')),
            'bankAccount' => trim($this->input->post('bankAccount')),
            'generateSeal' => $generateSeal,  //公司印章
            'registerNo' => $_POST['registerNo'] //统一社会信用代码
        ];


        if (!$data['generateSeal']) {
            unset($data['generateSeal']);
        }


//        print_r($data);
//        die();


        //是否会有添加失败的情况?
        $resultData = $this->supplier_model->edit($data, $where);

//        print_r($resultData);
//        die();

        if ($resultData) {
            redirect('/admin/supplier/index');
        } else {
            echo __alert('编辑失败');
        }

    }

    //编辑页面
    public function editView()
    {

        //读取用户名根据get id
        $arg = [
            'id' => $this->input->get('id')
        ];

        $data['list'] = $this->supplier_model->getByFieldQueryData('*', $arg, 0);

        //如果不存在直接跳转到404页面
        if (!$data['list']) {
            redirect('/home/error');
        }

        //根据供应商id去查询用户表的supplierId的用户名和密码
        $arg2 = [
            'supplierId' => $data['list']['id']
        ];
        $userData = $this->user_model->getByFieldQueryData('id,supplierId,username,password', $arg2, 0);

        $data['list']['supplierUser'] = $userData['username'];
        $data['list']['supplierPass'] = $userData['password'];

        $this->load->view('/admin/supplier/edit', $data);
    }

    //删除功能
    public function remove()
    {
        $postData = $this->input->post();

        if ($postData) {
            if (!$postData) {
                redirect('/admin/supplier/index?page=1');
            }

            $post = $this->input->post('del_id');
            foreach ($post as $v) {
                $where = [
                    'id' => $v
                ];

                $this->supplier_model->remove($where);
            }

            redirect('/admin/supplier/index?page=1');
        } else {
            $where = [
                'id' => $this->input->get('id')
            ];

            //是否会有添加失败的情况?
            $resultData = $this->supplier_model->remove($where);
            if ($resultData) {
                redirect('/admin/supplier/index?page=1');
            }
        }
    }

    //todo 导出功能
    public function daochu()
    {

        $this->load->library('Excels');

        //表格标题字段名
        $title = [
            0 => [
                0 => '序号',
                1 => '供应商编码',
                2 => '供应商名字',
                3 => '供应商简称',
                4 => '供应商联络人',
                6 => '联系号码',
                7 => '地址',
                8 => '创建时间',
                9 => '开户行',
                10 => '账号',
                11 => '社会统一识别码',
            ],
        ];

        //创建时间转化成正常时间
        $field = 'id,code,name,type,linkMan,phone,address,createTime,bank,bankAccount,registerNo';
        $data = $this->supplier_model->getData($field, 1);

        //大数组加上空格成为字符串
        foreach ($data as $k => $v) {
            $data[$k]['createTime'] = date('Y-m-d H:i:s', $v['createTime']);
            $data[$k]['bankAccount'] = $v['bankAccount'] . ' ';
            $data[$k]['registerNo'] = $v['registerNo'] . ' ';
        }

//        echo '<pre>';
//        print_r($data);
//        die;

        //表格内容
//        $content =  [
//            0 => [
//                0 => '序号',
//                1 => '供应商编码',
//                2 => '供应商名字',
//                3 => '供应商简称',
//                4 => '供应商联络人',
//                5 => '供应商联系人',
//                6 => '联系号码',
//                7 => '地址',
//                8 => '创建时间',
//                9 => 'size',
//                10 => 'nature',
//                11 => 'isProducers',
//                12 => 'vender',
//                13 => 'mail',
//                14 => 'note',
//        ],
//            1 => [
//                0 => '12312人',
//                1 => '所发生的丰富的',
//                2 => '积分高级人机'
//        ]];

        //二维数据
        $this->excels->exports($data, $title);

    }

    //评分接口
    public function score()
    {
//        报价系数=（基本情况分X30%+履约情况分X70%）/100

        $base = $_POST['base'];   //基本情况分
        $perform = $_POST['perform'];  //履约情况分
        $num = ($base * 0.3 + $perform * 0.7) / 100;

        $result = sprintf("%01.2f", $num * 100); //保留两位
        $result2 = $num * 100;  //整除或者保留一位

        $data = [
            'offerNum' => $result2 . '%'  //评分
        ];

        $where = [
            'id' => $_POST['id']
        ];

        $this->supplier_model->edit($data, $where);

        $a = [
            'success' => $result2 . '%'
        ];

        echo json_encode($a, JSON_UNESCAPED_UNICODE);
    }


}